package com.soft.small.app.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.soft.small.app.entity.AppClient;
import com.soft.small.util.encrypt.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

@Slf4j
public class AppMqttConnect extends BaseService{
    private AppClient appClient;
    private final static String model = "mqttConnect";

     public AppMqttConnect(AppClient appClient){
         this.appClient = appClient;
         setOptions();
     }

    public void setOptions(){
        log.info("++++++ APP客户端的信息是：{}",appClient.toString());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setMqttVersion(3);

        options.setUserName(appClient.getUsername());
        options.setPassword(appClient.getPassword().toCharArray());
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(30);
        //options.setMaxReconnectDelay(5);
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        //设置遗嘱
        String willTopic;
        if (appClient.getEnv().toLowerCase().endsWith("local")){
            willTopic = getATHTopic(appClient.getSn(),model,"lanAppOffLine");
        }else {
            willTopic = getATHTopic(appClient.getSn(),model,"appOffLine");
        }
        options.setWill(willTopic,getWillData(),1,true);
        log.info("设置遗嘱成功……{}",willTopic);
        appClient.setOptions(options);
    }

    public byte[] getWillData(){
        String lanAppOffLine = "{\"appVersion\":\"V5.00.001\",\"appSys\":\"android8.1.0\",\"userUnique\":\"\",\"sn\":\"\",\"appOemFirm\":\"0X8001\",\"appLanguage\":\"ZH_CN\",\"netWorkConnectionType\":\"wifi\"}";
        JSONObject lineStateJson = JSONUtil.parseObj(lanAppOffLine);
        lineStateJson.put("sn",appClient.getSn());
        if (appClient.getEnv().toLowerCase().endsWith("local")){
            lineStateJson.put("userUnique","uiot");
        }else {
            lineStateJson.put("userUnique",appClient.getUserUnique());
        }
        String willMsg = getSendData(appClient,lineStateJson.toString());
        log.info("遗嘱消息是……{}",willMsg);
        byte[] willMsgByte = SignUtil.getPublishMessage(willMsg,appClient.getAppSecret());
        return willMsgByte;
    }

}
